import React, { useState } from 'react';
import { useService, asCallService, useAsyncState } from 'hooklib/async';
import s from './common.less';
import { ShowAs, AsyncState } from './common';

function service1(req: any) {
  return Promise.resolve({ ...req, extra1: Date.now() })
}
function service2(req: any) {
  return Promise.resolve({ ...req, extra2: Date.now() })
}
const services = [service1, service2];

export default function CallServiceExample() {
  const [n, setN] = useState(0);
  const service = services[n];
  const as1 = useService([service], () => [
    service, {
      a: 1,
      b: 2,
    }
  ]);
  const toggle = () => setN(v => 1 - v);

  const as2 = useAsyncState('manual');
  const manualCallService = () => asCallService(as2, service1, { c: 3 });

  return (
    <div>
      <button onClick={toggle}>切换服务</button>
      <button onClick={manualCallService}>手动执行</button>
      <div className={s.grid}>
        <ShowAs as={as1} />
        <ShowAs as={as2} />
      </div>
    </div>
  )
}
